<template>
  <div class="post-create-container">
    <!-- 头部导航 -->
    <el-header class="post-header">
      <el-button @click="cancelPost">取消</el-button>
      <h2>发布笔记</h2>
      <el-button 
        type="primary" 
        :disabled="!canSubmit" 
        @click="submitPost"
      >
        发布
      </el-button>
    </el-header>

    <!-- 主要内容区域 -->
    <div class="post-content">
      <!-- 图片/视频上传 -->
      <div class="media-upload-section">
        <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :multiple="true"
          :limit="9"
          :on-change="handleMediaChange"
          :on-remove="handleMediaRemove"
          :file-list="mediaFiles"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <div class="upload-tips">最多上传9张图片或1个视频</div>
      </div>

      <!-- 标题输入 -->
      <div class="title-section">
        <el-input
          v-model="postForm.title"
          placeholder="添加标题，会有更多赞哦～"
          maxlength="30"
          show-word-limit
        />
      </div>

      <!-- 富文本编辑器 -->
      <div class="editor-section">
        <RichTextEditor 
          v-model="postForm.content"
          placeholder="分享你的心得..."
        />
      </div>

      <!-- 标签选择 -->
      <div class="tags-section">
        <el-select
          v-model="postForm.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="添加标签"
        >
          <el-option
            v-for="tag in popularTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </div>

      <!-- 位置信息 -->
      <div class="location-section">
        <el-input
          v-model="postForm.location"
          placeholder="添加位置"
          :suffix-icon="Location"
          @click="selectLocation"
        />
      </div>

      <!-- 高级选项 -->
      <div class="advanced-options">
        <el-collapse>
          <el-collapse-item title="更多选项">
            <div class="option-item">
              <span>谁可以看:</span>
              <el-radio-group v-model="postForm.visibility">
                <!-- 可见范围(1-公开,2-仅粉丝,3-仅好友,4-仅自己,5-指定用户) -->
                <el-radio label="1">公开</el-radio>
                <el-radio label="3">仅好友</el-radio>
                <el-radio label="4">仅自己</el-radio>
              </el-radio-group>
            </div>
            <div class="option-item">
              <el-checkbox v-model="postForm.allowComments">允许评论</el-checkbox>
            </div>
            <div class="option-item">
              <el-checkbox v-model="postForm.saveToDraft">保存为草稿</el-checkbox>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed,watch,onMounted } from 'vue'
import { Plus, Location } from '@element-plus/icons-vue'
import RichTextEditor from './RichTextEditor.vue'
import type { UploadFile, UploadFiles} from 'element-plus'
import   { ElMessage,ElMessageBox } from 'element-plus'
import request from '../utils/request';
import { useRouter, useRoute } from 'vue-router'
 import { useUserStore } from '../utils/userStore'
 const userStore = useUserStore()
 // 2. 创建响应式 users
const users = ref()
const mediaFiles = ref<UploadFile[]>([])
const popularTags = ref([
  '美食', '旅行', '穿搭', '美妆', '健身',
  '摄影', '家居', '读书', '电影', '音乐'
])
// 定义后端返回的标签数据结构
interface TagResponse {
  tagname: string;
}

// 查询tag标签表
const gettags = async () => {
  debugger;
  const res = await request.post('/xhs/tag/getTags',{'tagname':'name'})
  if (res.data && Array.isArray(res.data)) {
    popularTags.value = res.data.map((item: TagResponse) => item.tagname);
  }
}

// 3. 定义获取用户数据的函数
const fetchUsers = () => {
  
  const user = userStore.getUser
  users.value = user
  console.log(users.value)
}

onMounted(async () => {
  fetchUsers() //加载当前登录用户信息
  gettags()
})

// 当用户登录后状态变化时，重新加载数据
watch(
  () => userStore.getUser, // 监听用户状态变化
  () => {
    // 重新加载数据
    fetchUsers();
  }
);
 
const router = useRouter()
const route = useRoute()

// 表单数据类型
interface PostForm {
  title: string
  content: string
  media: File[]
  tags: string[]
  location: string
  userid: string
  visibility: '1' | '3' | '4'
  allowComments: boolean
  saveToDraft: boolean
}

// 响应式数据
const postForm = reactive<PostForm>({
  title: '',
  content: '',
  media: [],
  tags: [],
  location: '',
  userid: '',
  visibility: '1',
  allowComments: true,
  saveToDraft: false
})



// 计算属性 - 是否可以提交
const canSubmit = computed(() => {
  return (postForm.title.trim().length > 0 || 
          postForm.content.trim().length > 0) &&
         postForm.media.length > 0
})

// 处理媒体文件变化
const handleMediaChange = (file: UploadFile, fileList: UploadFiles) => {
  // 验证文件类型和大小
  if (!file.raw) {
    ElMessage.error('文件信息缺失，请重新选择文件');
    return false;
  }

  const isImage = file.raw.type.startsWith('image/');
  const isVideo = file.raw.type.startsWith('video/');
  const isLt10M = file.raw.size / 1024 / 1024 < 10;

  if (!isImage && !isVideo) {
    ElMessage.error('只能上传图片或视频!');
    return false;
  }

  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!');
    return false;
  }

  // 如果是视频且已经有其他文件
  if (isVideo && fileList.length > 1) {
    ElMessage.error('只能上传一个视频或最多9张图片!');
    return false;
  }

  postForm.media.push(file.raw as File);
  return true;
};
// 移除媒体文件
const handleMediaRemove = (file: UploadFile, fileList: UploadFiles) => {
  const index = postForm.media.findIndex(f => f.name === file.name)
  if (index !== -1) {
    postForm.media.splice(index, 1)
  }
}

// 选择位置
const selectLocation = () => {
  // 这里可以集成地图API
  //ElMessage.info('位置选择功能需要集成地图API')
}

// 取消发布
const cancelPost = () => {
  ElMessageBox.confirm('确定要取消发布吗? 内容将不会保存', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 返回上一页或关闭弹窗
    router.back()
  }).catch(() => {})
}

// 提交发布
const submitPost = async () => {
  try {
    const formData = new FormData()
    
    // 添加表单数据
    formData.append('title', postForm.title)
    formData.append('content', postForm.content)
    formData.append('tags', postForm.tags.join(','))
    formData.append('location', postForm.location)
    formData.append('userid', users.value.id );
    formData.append('visibility', postForm.visibility)
    formData.append('allowComments', String(postForm.allowComments))
    
    // 添加媒体文件
    postForm.media.forEach(file => {
      formData.append('media', file)
    })
    // 发送请求
    const response = await request.post('/xhs/main/saveMain', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    ElMessage.success('发布成功!')
    router.push('/discover')
  } catch (error) {
    ElMessage.error('发布失败，请稍后重试')
    console.error('发布错误:', error)
  }
}
</script>

<style lang="scss" scoped>
.post-create-container {
  max-width: 100%;
  margin: 0 auto;
  padding-bottom: 50px;
  
  .post-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    
    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }
  
  .post-content {
    padding: 15px;
    
    .media-upload-section {
      margin-bottom: 20px;
      
      .upload-tips {
        font-size: 12px;
        color: #999;
        margin-top: 8px;
      }
    }
    
    .title-section {
      margin-bottom: 20px;
    }
    
    .editor-section {
      margin-bottom: 20px;
    }
    
    .tags-section, .location-section {
      margin-bottom: 15px;
    }
    
    .advanced-options {
      margin-top: 30px;
      
      .option-item {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        
        span {
          margin-right: 15px;
          color: #666;
        }
      }
    }
  }
  
  // 覆盖element plus默认样式
  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
  
  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 100px;
    height: 100px;
  }
}
</style>